﻿using System.Linq;
using System.Windows.Input;
using Red.Controls.Depot.ViewModels;
using Red.Controls.Shell;
using Red.Core;

namespace Red.Controls.Depot.Dialogs
{
    public partial class SubmitWindow : RedWindow
    {
        #region Data

        private int _changelistId;

        #endregion Data

        #region Properties

        public int ChangelistId
        {
            get { return _changelistId; }
            set
            {
                if ( _changelistId == value )
                    return;

                _changelistId = value;
                OnChangelistIdChanged();
            }
        }

        public DepotInfo Depot { set; private get; }

        #endregion Properties

        #region C-tor

        public SubmitWindow()
        {
            InitializeComponent();
        }

        #endregion C-tor

        #region Event Handlers

        private void Submit_CanExecute( object sender, CanExecuteRoutedEventArgs e )
        {
            var submitViewModel = DataContext as ChangelistViewModel;
            e.CanExecute = !string.IsNullOrEmpty( submitViewModel.Description ) &&
                           submitViewModel.Files.Any( item => item.IsChecked );
        }

        private void Submit_Executed( object sender, ExecutedRoutedEventArgs e )
        {
            var submitViewModel = DataContext as ChangelistViewModel;

            var filesToRemove = from item in submitViewModel.Files where !item.IsChecked select item.Path;
            Depot.SourceControl.UpdateChangelist( ChangelistId, submitViewModel.Description, filesToRemove );
            Depot.SourceControl.SubmitChangelist( ChangelistId );

            DialogResult = true;
        }

        private void Save_CanExecute( object sender, CanExecuteRoutedEventArgs e )
        {
            e.CanExecute = true;
        }

        private void Save_Executed( object sender, ExecutedRoutedEventArgs e )
        {
            var submitViewModel = DataContext as ChangelistViewModel;
            var description = submitViewModel.Description;
            var filesToRemoveFromChangelist = submitViewModel.Files.Where( item => !item.IsChecked ).Select( item => item.Path );
            Depot.SourceControl.UpdateChangelist( _changelistId, description, filesToRemoveFromChangelist );
            DialogResult = true;
        }

        #endregion Event Handlers

        #region Private Methods

        private void OnChangelistIdChanged()
        {
            var submitViewModel = DataContext as ChangelistViewModel;
            submitViewModel.Description = Depot.SourceControl.GetChangelistDescription( _changelistId );
            submitViewModel.Files = Depot.SourceControl.GetChangelistFiles( _changelistId ).Select( item => new ChangelistFileInfo( submitViewModel ) { Path = item.DepotPath.Path } ).ToList();
        }

        #endregion Private Methods
    }
}
